'''获取tick数据流，一般情况下，数据生产商会提供stream数据进行实时推送，
如果没有，就需要定时请求获取数据
'''
import sys
sys.path.insert(0, '/home/yjj/xquant/')
sys.path.insert(0, '/opt/xquant/')
import v20
from event import TickEvent

class TickPrices(object):
    def __init__(self, domain, access_token, account_id,
                instruments, events_queue, asset = 'currency'):
        self.asset = asset
        self.domain = domain
        self.access_token = access_token
        self.account_id = account_id
        self.instruments = instruments
        self.events_queue = events_queue
        self._OAPI_URL = ["api-fxtrade.oanda.com",
                 "api-fxpractice.oanda.com"]
        self._OAPI_STREAM_URL = ["stream-fxtrade.oanda.com",
                        "stream-fxpractice.oanda.com"]
    def _to_queue(self):
        if self.domain == 'practice':
            self.oapi_stream = v20.Context(self._OAPI_STREAM_URL[1],
                                    poll_timeout = 1,
                                    port = 443,
                                    ssl = True,
                                    token = self.access_token,
                                    datetime_format = "UNIX")
        else:
            self.oapi_stream = v20.Context(self._OAPI_STREAM_URL[1],
                                    poll_timeout = 1,
                                    port = 443,
                                    ssl = True,
                                    token = self.access_token,
                                    datetime_format = "UNIX")
        response = self.oapi_stream.pricing.stream(
            self.account_id,
            instruments = self.instruments,
        )
        for msg_type, msg in response.parts():
            if msg_type == "pricing.Price":
                msg = msg.dict()
                if  msg['tradeable']:
                    instrument = msg["instrument"]
                    time = msg["time"]
                    bid = msg["bids"][0]['price']
                    ask = msg["asks"][0]['price']
                    tev = TickEvent(self.asset,instrument, time, bid, ask)
                    self.events_queue.put(tev)